package client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import pojo.ChessOnlineRoom;
import pojo.League;
import pojo.UserAccount;


import transfer.*;
import util.Utils;
import view.LobbyView;


import chessman.Chessman;


public class ClientWorker implements Runnable  {
	PrintWriter pw;
	BufferedReader br;
	Socket clientSocket;
	Client client;
	ObjectOutputStream oos;
	ObjectInputStream ois;

	public ClientWorker(Socket clientSocket,Client client) throws IOException {
		this.clientSocket = clientSocket;
		this.client = client;
		pw = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
		br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); 
		oos = new ObjectOutputStream(clientSocket.getOutputStream());
		ois = new ObjectInputStream(clientSocket.getInputStream());
		oos.flush();
		
		System.out.println("Connected Server!");
	}

	
	public void sendObject (Object obj){
		try {
			oos.reset();
			
			oos.writeObject(obj);
			oos.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public Object receiveObject (){
		Object obj = null;
		try {
			obj = ois.readObject();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return obj;
	}

	
	
	@Override
	public void run() {
		try {
			clientLoop();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				System.out.println("Server logoff!!!");
				clientSocket.close();
			} catch (IOException e) {
				
				e.printStackTrace();
			}
		}
	}

	private void clientLoop() throws IOException {
		while (true) {
			Data data;
			if ((data = (Data) receiveObject()) != null) {
				if(data.getHeader().equals("Account")){
					UserAccountData aData = (UserAccountData)data;
					UserAccount acc = aData.getAcc();
					if(acc != null ){
						Utils.saveUserSession(aData.getAcc().getUsername());
						System.out.println(Utils.getCurrentUser());
						client.setAcc(aData.getAcc());
						client.showLobbyView(false);
					}
					else{
						client.getmHomePageView().getRegisterForm().setInvalidUserError();
					}
				}
				if(data.getHeader().equals("List Rooms")){
					RoomData rData = (RoomData)data;
					System.out.println("list room: " + rData.getRooms().size());
					ArrayList<ChessOnlineRoom> list = rData.getRooms();
					LobbyView.rooms = list;
					if(client.getmLobbyView() != null){
						client.getmLobbyView().showRoom();
						
					}			
				}
				if(data.getHeader().equals("Your Room")){
					
					IntegerData iData = (IntegerData) data;
					int roomID = iData.getNum();
					Utils.currentRoomID = roomID;
					client.showRoomView(LobbyView.rooms.get(roomID));
				}
				if(data.getHeader().equals("Close Your Room")){
					IntegerData iData = (IntegerData) data;
					Utils.currentRoomID = -1;
					if(iData.getNum() == 0) client.showLobbyView(false);
					else client.showLobbyView(true);
				}
				if(data.getHeader().equals("Can Join")){
					IntegerData iData = (IntegerData) data;
					int roomID = iData.getNum();
					Utils.currentRoomID = roomID;
					client.showRoomView(LobbyView.rooms.get(roomID));
				}
				if(data.getHeader().equals("Update Room")){
					IntegerData iData = (IntegerData) data;
					client.showRoomView(LobbyView.rooms.get(iData.getNum()));
				}
				if(data.getHeader().equals("Can Quit")){
					IntegerData iData = (IntegerData) data;
					Utils.currentRoomID = -1;
					if(iData.getNum() == 0) client.showLobbyView(false);
					else client.showLobbyView(true);
				}
				if(data.getHeader().equals("Your team is A")){
					client.loadTeamA(client);
				}
				if(data.getHeader().equals("Your team is B")){
					client.loadTeamB(client);
				}
				if(data.getHeader().equals("Current turn")){
					IntegerData iData = (IntegerData)data;
        			int currentTurn = iData.getNum();
        			System.out.println("turn hien tai la " + currentTurn);
        			client.setCurrentTurn(currentTurn);
        			client.refreshLabelTurn(currentTurn);
        		}
				if(data.getHeader().equals("Refresh board")){
					ChessData cData = (ChessData)data;
					Chessman[] chess = cData.getArrayChess();
					if(chess != null){
						client.refreshBoard(chess);
						System.out.println("util room" +Utils.currentRoomID);
						sendObject(new IntegerData("Get new turn",Utils.currentRoomID));
					}
				}
				if(data.getHeader().equals("Chat content")){
					StringData sData = (StringData)data;
					client.appenChatString(sData.getContent());
				}
				if(data.getHeader().equals("You win")){
					UserAccountData uData = (UserAccountData)data;
					client.setAcc(uData.getAcc());
					Utils.currentRoomID = -1;
					client.showLobbyView(false);
				}
				if(data.getHeader().equals("You lose")){
					UserAccountData uData = (UserAccountData)data;
					client.setAcc(uData.getAcc());
					Utils.currentRoomID = -1;
					client.showLobbyView(false);
				}

				if(data.getHeader().equals("Disconnect")){
					break;
				}

				if(data.getHeader().equals("List Leagues")){
					LeagueData lData = (LeagueData)data;
					if(client.getAcc() != null && lData.getAcc().getUsername().equals(client.getAcc().getUsername()))
					{
						System.out.println("list league: " + lData.getLeagues().size());
						ArrayList<League> list = lData.getLeagues();
						LobbyView.leagues = list;
						if(client.getmLobbyView() != null){
							client.getmLobbyView().showLeague();
						}
					}
				}
				
				if(data.getHeader().equals("Show League Lobby View")){
					//UserAccountData accData = (UserAccountData)data;
					//if(client.getAcc() != null && accData.getAcc().getUsername().equals(client.getAcc().getUsername()))
						client.showLobbyView(true);
				}
				
				if(data.getHeader().equals("List League Rooms")){
					LeagueRoomData lrData = (LeagueRoomData)data;
					System.out.println("Compare League Id: " + lrData.getLeagueId() + " - " + Utils.getLeagueId());
					if(lrData.getLeagueId() == Utils.getLeagueId()){
						ArrayList<ChessOnlineRoom> list = lrData.getRooms();
						ArrayList<ChessOnlineRoom> list_leaguerooms = new ArrayList<ChessOnlineRoom>();
						
						for(ChessOnlineRoom i : list)
							if(i != null && i.isLeague() && i.getLeagueId() == lrData.getLeagueId())
								list_leaguerooms.add(i);
						
						LobbyView.rooms = list;
						LobbyView.leaguerooms = list_leaguerooms;
						
						System.out.println("Current List Rooms: " + LobbyView.rooms.size());
						System.out.println("Current List League Rooms: " + LobbyView.leaguerooms.size());
						if(client.getmLobbyView() != null){
							client.getmLobbyView().showLeagueRooms(lrData.getLeagueId());
						}
					}
				}
				
			}
		}
	}
	

}
